﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;

namespace SortOf
{
    public static class CodeTijdmeting
    {
        [DllImport("kernel32.dll")]
        extern static short QueryPerformanceCounter(ref long x);

        [DllImport("kernel32.dll")]
        extern static short QueryPerformanceFrequency(ref long x);

        [DllImport("kernel32.dll")]
        static extern IntPtr GetCurrentThread();

        [DllImport("kernel32.dll")]
        static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);

        private static long start = 0, end = 0, freq = 0;

        /*
         * This method starts the time measuring.
         */
        public static void begin()
        {
            QueryPerformanceCounter(ref start);
        }


        /*
         * This method stops the time measuring.
         */
        public static void stop()
        {
            QueryPerformanceCounter(ref end);
        }

        /*
         * This method must be run before starting a time measuring
         */
        public static void setup()
        {
            Process thisProc = Process.GetCurrentProcess();
            thisProc.PriorityClass = ProcessPriorityClass.RealTime;
            SetThreadAffinityMask(GetCurrentThread(), new IntPtr(2));
            QueryPerformanceFrequency(ref freq);
        }

        /*
         * This method resets the time measuring class.
         */
        public static void reset()
        {
            freq = 0;
            start = 0;
            end = 0;
            setup();
        }

        /*
         * After a test this method gets the results in Seconds
         */
        public static float getResultNanoSecond()
        {
            return ((Convert.ToSingle(end) - Convert.ToSingle(start)) * 1 / Convert.ToSingle(freq)) * 1000000000;
        }

        /*
         * This method gets the start time in the QueryPreformanceCounter
         */
        public static long getStart()
        {
            return start;
        }

        /*
         * This method gets the end time in the QueryPreformanceCounter
         */
        public static long getEnd()
        {
            return end;
        }

        /*
         * This method gets the frequency of the CPU
         */
        public static long getFrequency()
        {
            return freq;
        }
    }
}
